<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/4/9
 * Time: 17:51
 */
declare(strict_types = 1);
namespace app\mobile\middleware;

use Closure;
use think\Config;
use think\Request;
use think\Response;

class AllowCrossDomain
{

    protected $cookieDomain;
    
    // header头配置
    protected $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age' => 1800,
        'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,token'
    ];

    /**
     * AllowCrossDomain constructor.
     *
     * @param Config $config            
     */
    public function __construct(Config $config)
    {
        $this->cookieDomain = $config->get('cookie.domain', '');
    }

    public function handle($request, Closure $next)
    {
        
        // 处理跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Max-Age: 1800');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, access-token');
        // 第一次预请求不管
        if (strtoupper($request->method()) == "OPTIONS") {
            exit();
        }
        // 处理跨域
        // 后置中间件
        $response = $next($request);
        return $response;
    }
}